package com.codyy.felix.webconsole.plugins.route.rest;

import com.codyy.felix.webconsole.plugins.route.core.ProcessorService;
import com.codyy.felix.webconsole.plugins.route.core.pojo.RouteParams;
import com.codyy.felix.webconsole.plugins.route.core.pojo.RouteProgress;
import com.codyy.felix.webconsole.plugins.route.utils.JsonUtils;
import org.osgi.framework.BundleContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

import static com.codyy.felix.webconsole.plugins.route.utils.JsonUtils.writeMessage;

/**
 * @author : issac
 * create at:  2019-04-23  14:35
 * @description:
 */
public class ProcessorServlet extends RestServlet {

    private static final String ALIAS_NAME = "proc";
    private final ProcessorService processorService;


    @Override
    protected String getAliasName() {
        return ALIAS_NAME;
    }

    public ProcessorServlet(BundleContext bundleContext) {

        super(bundleContext);
        this.processorService = new ProcessorService(bundleContext);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String phrase = getPhrase(request);
        final List<String> providers = getProviders(request);
        final RouteParams params = new RouteParams(phrase, providers, getResultLimit(request), getCached(request));
        final RouteProgress progress = processorService.list(params);
        writeMessage(response, JsonUtils.MessageType.SUCCESS, "Results found", progress);


    }

    private void personalizeResult(HttpServletResponse response, RouteParams params) throws IOException {
        response.setHeader("Content-Disposition", String.format("attachment; filename='route_%s.json'", params.getPhrase()));
        personalizeResult(response, params);
        final RouteProgress progress = processorService.list(params);

        writeMessage(response, JsonUtils.MessageType.SUCCESS, "Results found", progress);
    }

}
